package com.whitecat.voting.service;

import com.github.pagehelper.PageHelper;
import com.whitecat.voting.common.Paged;
import com.whitecat.voting.constant.SysConstant;
import com.whitecat.voting.dao.VotingRecordMapper;
import com.whitecat.voting.entity.MpUserInfo;
import com.whitecat.voting.entity.VotingRecord;
import com.whitecat.voting.exception.BusinessException;
import com.whitecat.voting.util.BeanMapUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class VotingRecordService {

    private final VotingRecordMapper votingRecordMapper;
    private final MpUserInfoService mpUserInfoService;

    public VotingRecordService(VotingRecordMapper votingRecordMapper, MpUserInfoService mpUserInfoService) {
        this.votingRecordMapper = votingRecordMapper;
        this.mpUserInfoService = mpUserInfoService;
    }

    public int countVotesByOpenId(String openId) {
        return votingRecordMapper.countVotesByOpenId(openId);
    }

    public List<VotingRecord> getByCondition(Map<String, Object> condition) {
        PageHelper.startPage(condition);
        //TODO 稍微复杂一点的查询请使用MyBatis原生的xml
        return votingRecordMapper.select(BeanMapUtils.mapToBean(condition, new VotingRecord()));
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean add(String candidateId, String votersId) {
        MpUserInfo candidate = mpUserInfoService.findById(candidateId);
        if (candidate == null) {
            log.error("invalid candidate id: [{}]", candidateId);
            throw new BusinessException("无效的候选人ID！");
        }
        MpUserInfo voters = mpUserInfoService.findById(votersId);
        if (voters == null) {
            log.error("invalid voters id: [{}]", votersId);
            throw new BusinessException("无效的投票人ID！");
        }

        long count = votingRecordMapper.countVoteTimesToday(votersId);
        if (count > SysConstant.VOTING_FREQ_LIMIT) {
            log.error("voting freq out of limit for voters id: [{}]", votersId);
            throw new BusinessException("超过最大投票次数限制！");
        }

        VotingRecord entity = new VotingRecord();
        entity.setCandidate(candidateId);
        entity.setVoters(votersId);
        return votingRecordMapper.insert(entity) > 0;
    }
}
